package com.onetech.adrewards.free.activities;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.dialogs.UpdateDialog;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.StartUpDTO;
import com.onetech.adrewards.free.pushnotification.PushNotificationHelper;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.todddavies.components.progressbar.ProgressWheel;

public class SplashScreenActivity extends BaseActivity {
	private  final int SPLASH_DISPLAY_TIME = 2000;
	private TextView mVersionName=null;
	
	private CheckAppData mCheckAppData=null;
	private ProgressWheel mProgressBar=null;
	private Button mRetryBtn=null;
	private TextView mErrorMessage=null;
	private StartUpDTO mResult=null;
	private RegisterGCMTask mRegisterGCMTask=null;
	
	public interface ExitDialogHandler{
    	public void doExit(boolean isForceUpdate);
    	public void go2HomeActivity();
    }
    private ExitDialogHandler mHandler=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_activity_layout);
		mVersionName=(TextView)findViewById(R.id.txtViewVersion);
		mProgressBar=(ProgressWheel)findViewById(R.id.splashProgressBar);
		mProgressBar.setText("");
		mProgressBar.setContourColor(Color.TRANSPARENT);
		//mProgressBar.spin();
		
		mRetryBtn=(Button)findViewById(R.id.errorStartUpBtn);
		mErrorMessage=(TextView)findViewById(R.id.errorStartUpMessage);
		String verName=AdrewadsUtils.getVersionName(getApplicationContext());
		if(verName!=null){
			mVersionName.setText(verName);
		}					
		showHideNotFoundView(true, false);	
		mRetryBtn.setOnClickListener(this);		
		mHandler=new ExitDialogHandler() {
			@Override
			public void doExit(boolean isForceUpdate) {
				if(isForceUpdate){
					finish();
				}
			}

			@Override
			public void go2HomeActivity() {
				go2HomePage();
			}
		};
		
		
		
		catchSchemaUrl();
		
		
	}
	
	private void catchSchemaUrl()
	{
		Uri uri = getIntent().getData();
		if(uri != null)
		{
			String action = uri.getQueryParameter("action");
			
			if("getcoin".equals(action))
			{
				String memId = uri.getQueryParameter("mem_id");
				String inviteCode = uri.getQueryParameter("invite_code");
				String coin = uri.getQueryParameter("coin");
				Intent intent= new Intent(getApplicationContext(), InviteGetPointActivity.class);
				intent.putExtra("memId", memId);
				intent.putExtra("inviteCode", inviteCode);
				intent.putExtra("coin", coin);
				startActivity(intent);
				finish();
			}
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			@Override
			public void run() {
				checkNetwork();
			}
		}, SPLASH_DISPLAY_TIME);
	}
	private void checkData(){
		if(mCheckAppData==null || mCheckAppData.getStatus()==Status.FINISHED){
			mCheckAppData=new CheckAppData();
			mCheckAppData.execute();
		}
	}
	private class CheckAppData extends AsyncTask<Void, Void, StartUpDTO>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mErrorMessage.setText("");
			showHideNotFoundView(true, false);
		}
		@Override
		protected StartUpDTO doInBackground(Void... arg0) {
			try {
				boolean isStartUp=AdrewadsUtils.checkStartUp(SplashScreenActivity.this);
				String uid=AdrewadsUtils.getUserId(SplashScreenActivity.this, true, "");
				if(uid!=null && uid.trim().length()<1){
					uid=null;
				}
				return CommonModel.getInstance().getStartUpData(uid,isStartUp);
			} catch (Exception e) {
				return null;
			}
		}
		@Override
		protected void onPostExecute(StartUpDTO result) {
			super.onPostExecute(result);
			try {
				if(result!=null){
					
				/*Testing show send mail
				//	Intent mSendMail=new Intent(getApplicationContext(), LoginInviteCodeSendMailActivity.class);
				//	startActivity(mSendMail);
				//	finish();
					
					Intent intent= new Intent(getApplicationContext(), InviteGetPointActivity.class);
					intent.putExtra("memId", "76a8aa0cfe2fa12b2b54154a7fb6490e");
					intent.putExtra("inviteCode", "1234");
					intent.putExtra("coin", "20");
					startActivity(intent);
					finish();
					
				*/	
					//result.setLogin_bonus_flag("1");
					//result.setErr_code("002-00500");
					if(result.getErr_code().trim().equals("002-005")){
						Intent mRegisterIntent=new Intent(getApplicationContext(), LoginInviteCodeActivity.class);
						startActivity(mRegisterIntent);
						finish();
					}
					else{
						mResult=result;
						AppConfig.config=result;
						AppConfig.uId=result.getMem_id();
						AdrewadsUtils.getUserId(SplashScreenActivity.this, false, AppConfig.uId);
						if(result.getToken()!=null){
							AppConfig.token=result.getToken();
						}
						if(!TextUtils.isEmpty(AppConfig.uId))
						{
							DoRegisterGCM();
						}
//						if(result.getTotal_coin()!=null && result.getTotal_coin().length()>0){
//							AppConfig.userCoins=Integer.valueOf(result.getTotal_coin());
//						}
						if(result.getExchange_coin_limit()!=null&&result.getExchange_coin_limit().trim().length()>0){
							AppConfig.MIN_COIN_EXCHANGE=Integer.valueOf(result.getExchange_coin_limit());
						}
						
						if(result.getBonus_max_coin()!=null&&result.getBonus_max_coin().trim().length()>0){
							AppConfig.BONUS_MAX_COIN = Integer.valueOf(result.getBonus_max_coin());
						}
						
						if(result.getAd_sort() !=null && result.getAd_sort().trim().length()>0){
							AppConfig.AD_SORT = Integer.valueOf(result.getAd_sort());
						}
						
						if(result.getLogin_bonus_flag().trim().equals("0")){
							AppConfig.LOGIN_BONUS=false;
						}else{
							AppConfig.LOGIN_BONUS=true;
						}
						//result.setMaintenance_flag("1");
						if(result.getMaintenance_flag().trim().equals("0")){
							//result.setNew_version_flag("1");
							//result.setForce_update_flag("1");
							//result.setForce_update_target_version("2.0");
							if(!result.getNew_version_flag().trim().equals("0")){
								if(!AdrewadsUtils.checkCurrentVersion(getApplicationContext(), result.getForce_update_target_version())){
									boolean isForceUpdate=(!result.getForce_update_flag().trim().equals("0"));
									UpdateDialog mUpdateDialog=new UpdateDialog(SplashScreenActivity.this, isForceUpdate, result.getNew_version_url(),mHandler);
									mUpdateDialog.show();
								}else{
									go2HomePage();
								}
							}else{
								go2HomePage();
							}
						}else{
							//maintenance server
							mErrorMessage.setText(getString(R.string.server_error_message));
							showHideNotFoundView(false, true);						
						}
					}
					
					
				}else{
					mErrorMessage.setText(getString(R.string.not_found_data_message));
					showHideNotFoundView(false, true);
				}
				
				
			} catch (Exception e) {
				showHideNotFoundView(false, true);
			}
			//go2HomePage(result);			
		}
	}
	
	private void checkNetwork(){
		if(AdrewadsUtils.isOnline(getApplicationContext())){
			mErrorMessage.setText("");
			checkData();
		}else{
			mErrorMessage.setText(getString(R.string.network_not_found_message));
			showHideNotFoundView(false, true);
		}
	}
	@Override
	public void onClick(View v) {
		int id=v.getId();
		switch (id) {
		case R.id.errorStartUpBtn:
			checkNetwork();
			break;

		default:
			break;
		}
	}
	private void showHideNotFoundView(boolean showProgressBar,boolean showRetryBtn){
		mRetryBtn.setVisibility(showRetryBtn?View.VISIBLE:View.INVISIBLE);
		mProgressBar.setVisibility(showProgressBar?View.VISIBLE:View.INVISIBLE);
		if(showProgressBar){
			mProgressBar.spin();
		}else{
			mProgressBar.stopSpinning();
		}
	}
	public void go2HomePage(){
		try {
			Intent intent=new Intent(getApplicationContext(), BaseNewActivity.class);
			//Intent intent=new Intent(getApplicationContext(), HomeActivity.class);
//			intent.putExtra("m_id", "2835");
//			intent.putExtra("m_owner_id", "558");
			if(mResult!=null && mResult.getMem_id()!=null && mResult.getMem_id().trim().length()>0){
				AppConfig.uId=mResult.getMem_id().trim();
				intent.putExtra("user_id", mResult.getMem_id().trim());
				intent.putExtra("uid", mResult.getMem_id().trim());
			}
			/*
			intent.putExtra("platform_id", "0");
			intent.putExtra("url", "http://car.mobadme.jp/spg/spnew/558/2835/index.php");
			intent.putExtra("api_key", "76552d4faa4dd35b");
			intent.putExtra("app_key", "ncIdX3la");
			intent.putExtra("loading_msg", "loading..");
			intent.putExtra("timeout", "3000");

			////
			
			intent.putExtra("appkey", "ncIdX3la");
			////

			intent.putExtra("show_button", true);
			intent.putExtra("button_string", "back");
			intent.putExtra("bk_color", Color.BLUE);
			intent.putExtra("button_gravity", Gravity.RIGHT);
			*/
			mProgressBar.stopSpinning();
			startActivity(intent);
			finish();
		} catch (Exception e) {
			return;
		}
	}
	private void DoRegisterGCM(){
		if(mRegisterGCMTask==null || mRegisterGCMTask.getStatus()==Status.FINISHED){
			mRegisterGCMTask=new RegisterGCMTask();
			mRegisterGCMTask.execute();
		}
	}
	private void registerGCM() {
		try {
			PushNotificationHelper.getInstance(getApplicationContext()).register();
		} catch (Exception e) {
			return;
		}
	}
	private class RegisterGCMTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			registerGCM();
			return null;
		}
		
	}
}
